from functools import wraps
from flask import request, jsonify, g
import jwt
from models import User
from utils.res import api_response  # 统一返回格式
from flask import current_app as app

def token_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        token = request.headers.get('Authorization')  # 从请求头读取 Authorization 字段
        if not token:
            return api_response(401, "令牌丢失", None)

        try:
            # 拆掉 "Bearer " 前缀
            token = token.split(" ")[1]
            data = jwt.decode(token, app.config['JWT_SECRET_KEY'], algorithms=["HS256"])
            user_id = data['user_id']

            # 查询用户是否存在
            user = User.query.get(user_id)
            if not user:
                return api_response(401, "令牌无效", None)

            # 把当前用户临时存储到 g 对象中，供视图函数使用
            g.current_user = user

        except jwt.ExpiredSignatureError:
            return api_response(401, "令牌已过期", None)
        except jwt.InvalidTokenError:
            return api_response(401, "令牌无效", None)
        except Exception:
            return api_response(401, "令牌解析失败", None)

        return f(*args, **kwargs)

    return decorated
